﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using FimetContoDeposito.BLL.Facades;
using FimetContoDeposito.BLL.Metadata;
using FimetContoDeposito.DAL;
using GrayParrot.Core;
using GrayParrot.Core.Json;
using GrayParrot.Web.Controls;
using GrayParrot.Web.Formly;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FimetContoDeposito.Controllers
{
    public class FornitoreArticoliController : GridCrudController<JObject, DTParameters>
    {
        #region Loading Fields...
        [HttpGet]
        public string LoadFields()
        {
            string retValue = null;

            var m_fields = FormlyHelper.ToFormly<ArticoliPerFornitoriMetadata>(typeof(ArticoliPerFornitoriMetadata));

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new NullToEmptyListResolver();
            settings.Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false } };
            settings.Formatting = Formatting.Indented;
            settings.NullValueHandling = NullValueHandling.Ignore;

            retValue = JsonConvert.SerializeObject(m_fields, settings);

            return retValue;
        }

        [HttpGet]
        public string[] LoadFields(Guid idF, Guid idA)
        {
            string[] retValue = new string[2] { string.Empty, string.Empty };

            FCD_ArticoliPerFornitori obj = null;
            using (ArticoliPerFornitoreFacade m_dc = ArticoliPerFornitoreFacade.Create())
            {
                ReturnValue<FCD_ArticoliPerFornitori> m_objs = m_dc.Get(idA, idF);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }
            }

            if (obj != null)
            {
                var m_fields = FormlyHelper.ToFormly<ArticoliPerFornitoriMetadata>(typeof(ArticoliPerFornitoriMetadata));

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new NullToEmptyListResolver();
                settings.Converters = new List<JsonConverter> { 
                    new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false }
                };

                settings.Formatting = Formatting.Indented;
                settings.NullValueHandling = NullValueHandling.Ignore;

                retValue[0] = JsonConvert.SerializeObject(m_fields, settings);

                retValue[1] = JsonConvert.SerializeObject(obj);
            }
            else
            {
            }

            //
            return retValue;
        }
        #endregion

        public override HttpResponseMessage Delete(JObject data)
        {
            throw new NotImplementedException();
        }

        public override System.Net.Http.HttpResponseMessage Add(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;

            Guid m_idArticolo = Guid.Parse(json.idA.ToString());
            Guid m_idFornitore = Guid.Parse(json.IdFornitore.ToString());
            string m_note = json.Note;
            decimal m_prezzoUnitario = decimal.Parse(json.PrezzoUnitario.ToString());
            decimal m_scontoFornitore = decimal.Parse(json.ScontoFornitore.ToString());
            decimal m_scortaMinima = decimal.Parse(json.ScortaMinima.ToString());

            using (ArticoliPerFornitoreFacade m_apff = ArticoliPerFornitoreFacade.Create())
            {
                FCD_ArticoliPerFornitori obj = new FCD_ArticoliPerFornitori();
                obj.IdArticolo = m_idArticolo;
                obj.IdFornitore = m_idFornitore;
                obj.Note = m_note;
                obj.PrezzoUnitario = m_prezzoUnitario;
                obj.ScontoFornitore = m_scontoFornitore;
                obj.ScortaMinima = m_scortaMinima;

                ReturnValue<bool> result = m_apff.Add(obj);

                if (result.HasValue)
                {
                    if (result.Value)
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Dati Fornitore aggiunti");
                    }
                    else
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Errore inserimento di Dati Fornitore");
                    }
                }
                else
                {
                    if (result.HasError)
                    {
                        string msg = string.Format("Errore inserimento dati fornitore: {0}", result.Error.Message);
                        retValue = Request.CreateResponse(HttpStatusCode.OK, msg);
                    }
                }
            }

            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Edit(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;

            Guid m_idArticolo = Guid.Parse(json.idA.ToString());
            Guid m_idFornitore = Guid.Parse(json.IdFornitore.ToString());
            string m_note = json.Note;
            decimal m_prezzoUnitario = decimal.Parse(json.PrezzoUnitario.ToString());
            decimal m_scontoFornitore = decimal.Parse(json.ScontoFornitore.ToString());
            decimal m_scortaMinima = decimal.Parse(json.ScortaMinima.ToString());

            using (ArticoliPerFornitoreFacade m_apff = ArticoliPerFornitoreFacade.Create())
            {
                FCD_ArticoliPerFornitori obj = null;
                ReturnValue<FCD_ArticoliPerFornitori> m_objs = m_apff.Get(m_idArticolo, m_idFornitore);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }

                obj.IdArticolo = m_idArticolo;
                obj.IdFornitore = m_idFornitore;
                obj.Note = m_note;
                obj.PrezzoUnitario = m_prezzoUnitario;
                obj.ScontoFornitore = m_scontoFornitore;
                obj.ScortaMinima = m_scortaMinima;

                ReturnValue<bool> result = m_apff.Edit(obj);

                if (result.HasValue)
                {
                    if (result.Value)
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Dati Fornitore modificati");
                    }
                    else
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Errore nella modifica dei Dati Fornitore");
                    }
                }
                else
                {
                    if (result.HasError)
                    {
                        string msg = string.Format("Errore modifica dati fornitore: {0}", result.Error.Message);
                        retValue = Request.CreateResponse(HttpStatusCode.OK, msg);
                    }
                }
            }

            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Delete(int id)
        {
            throw new NotImplementedException();
        }

        public override System.Net.Http.HttpResponseMessage Load(DTParameters data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            //using (AnagraficaArticoliFacade m_dc = AnagraficaArticoliFacade.Create())
            //{
            //    ReturnValue<IQueryable<ArticoloBag>> m_objs = m_dc.GetAllArticoliBag();

            //    DTResult<ArticoloBag> result = DTResult<ArticoloBag>.Empty("Nessun elemento trovato");
            //    if (m_objs.HasValue)
            //    {
            //        AnagraficaArticoliResultSet m_rs = new AnagraficaArticoliResultSet(data, m_objs.Value);
            //        result = m_rs.GetResult();
            //    }
            //    else
            //    {
            //        if (m_objs.HasError)
            //        {
            //            result.Message.MessageType = MessageTypes.Error;
            //            result.Message.Message = m_objs.Error.Message;
            //        }
            //    }

            //    retValue = Request.CreateResponse(HttpStatusCode.OK, result);
            //}

            return retValue;
        }

        [HttpPost]
        public List<NameValue<string, Guid>> LoadArticoli(JObject data)
        {
            List<NameValue<string, Guid>> retValue = null;

            dynamic json = data;
            Guid m_id = Guid.Parse(json.parameters[0].ToString());

            using (ArticoliPerFornitoreFacade m_cf = ArticoliPerFornitoreFacade.Create())
            {
                var objs = m_cf.GetAll(m_id);

                if (objs.HasValue)
                {
                    if (objs.Value.Any())
                    {
                        retValue = objs.Value.ToList();
                    }
                }
            }

            return retValue;
        }

        [HttpPost]
        public List<NameValue<string, Guid>> LoadCodiciArticoli(JObject data)
        {
            List<NameValue<string, Guid>> retValue = null;

            dynamic json = data;
            Guid m_id = Guid.Parse(json.parameters[0].ToString());

            using (ArticoliPerFornitoreFacade m_cf = ArticoliPerFornitoreFacade.Create())
            {
                var objs = m_cf.GetAllCodice(m_id);

                if (objs.HasValue)
                {
                    if (objs.Value.Any())
                    {
                        retValue = objs.Value.ToList();
                    }
                }
            }

            return retValue;
        }
    }
}